package com.example.rabbitmq.util;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ConnectionUtil2 {
    private static ConnectionFactory connectionFactory;
    private static Connection connection;
    /**
     * 建立与RabbitMQ的连接
     */
    public static Connection getConnection() throws TimeoutException, IOException {
        if (connectionFactory==null){
            //定义连接工厂
            connectionFactory=new ConnectionFactory();
            //设置服务地址
            connectionFactory.setHost("101.133.174.208");
            //端口
            connectionFactory.setPort(5672);
            //设置账号信息，用户名、密码、vhost
            connectionFactory.setVirtualHost("/");  //   现在 web  管理平台创建虚拟机
            connectionFactory.setUsername("admin");
            connectionFactory.setPassword("admin");
        }

        if (connection==null || !connection.isOpen()){
            connection= connectionFactory.newConnection();
        }
        // 通过工程获取连接
        return connection;
    }
}
